<?php
namespace Admin\Pages;
/**
 * Description of Categories
 *
 * @author nofear
 */
class Categories extends Page {
    
    public function index() {
        $this->view = new \System\Template('@admin/Categories/list.twig');
        $categories = $this->EntityManager->getRepository('Shared\Main\Category')->findAll();
        
        $this->view->categories = $categories;
    }
    
    public function edit($id = null) {
        $this->view = new \System\Template('@admin/Categories/form.twig');
        
        if ($id) {
            $Category = $this->EntityManager->find('Shared\Main\Category', $id);
        } else {
            $Category = new \Shared\Main\Category();
        }
        
        $this->view->form = new \Admin\Forms\Category($Category);
    }
    
    public function save() {
        $id = trim($this->request->get('id'));
        $name = trim($this->request->get('name'));
        
        if ($name) {
            if ($id) {
                $Category = $this->EntityManager->find('Shared\Main\Category', $id);
            } else {
                $Category = new \Shared\Main\Category;
                $Category->setKey(strtolower($this->sanitize($name)));
            }
            
            $Category->setName($this->sanitize($name));

            $this->EntityManager->persist($Category);
            $this->EntityManager->flush();
        }
        
        $this->redirect($this->generateUrl('admin_categories'));
    }
    
    public function delete($id) {
        $Category = $this->EntityManager->find('Shared\Main\Category', (int) $id);
        $this->EntityManager->remove($Category);
        $this->EntityManager->flush();
        
        $this->redirect($this->generateUrl('admin_categories'));
    }
}
